﻿using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Neo4jConnect
{
    public class LuceneIndexService : IIndexService
    {
        private readonly GraphDatabaseService graphDatabaseService;

        public LuceneIndexService(IGraphDatabaseService graphDatabaseService)
        {
            this.graphDatabaseService = (GraphDatabaseService)graphDatabaseService;

            dynamic obj = new JObject();
            obj.name = "fulltext";
            obj.config = new JObject();            
            obj.config.type = "fulltext";
            obj.config.provider = "lucene";

            var json = JsonConvert.SerializeObject(obj);
            this.graphDatabaseService.RestService.Index.AddIndex(json);
        }

        public void AddIndex(Node node, string key)
        {
            graphDatabaseService.RestService.Index.AddIndexToNode("fulltext", node.Id, key, node.GetProperty(key));
        }

        public IEnumerable<Node> GetNodes(string key, string value)
        {
            string json = graphDatabaseService.RestService.Index.QueryIndex("fulltext", key, value);

            foreach (JToken jsonNode in JArray.Parse(json).Cast<JToken>())
            {
                Node node = new Node();
                node.Init(graphDatabaseService);
                node.ReadJson(jsonNode);
                yield return node;
            }
        }
    }
}
